package com.chenwang.front.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * <b>功能：</b> Connection操作工具类<br>
 * <b>作者：</b>王春阳<br>
 * <b>日期：</b>2017年3月11日 下午12:21:24
 *
 * @version 1.0 <br>
 */
public class ConnectionUtil {
    /**
     * <b>功能：</b> java发送post请求 流形式<br>
     * <b>作者：</b>王春阳<br>
     * <b>日期：</b> 2017年8月19日 上午1:19:22 <br>
     *
     * @param url        链接地址
     * @param jsonString 上传的数据 json字符串
     * @return
     * @throws IOException
     */
    public static Object DoPostStream(String url, String jsonString) throws Exception {
        BufferedReader reader = null;
        String response = "";
        OutputStream out = null;
        try {
            System.out.println("url----" + url);
            // 创建URL
            URL httpUrl = new URL(url);
            // 建立连接
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "utf-8");
            // 设置文件类型:
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            // 设置接收类型否则返回415错误
            //conn.setRequestProperty("accept","*/*");//此处为暴力方法设置接受所有类型，以此来防范返回415;
            conn.setRequestProperty("accept", "application/json");
            //conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 往服务器里面发送数据
            byte[] writebytes = jsonString.getBytes();
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
            OutputStream outwritestream = conn.getOutputStream();
            outwritestream.write(writebytes);
            outwritestream.flush();
            outwritestream.close();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                response += lines;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response;
    }

    /**
     * <b>功能：</b> java发送post请求 数据字符形式<br>
     * <b>作者：</b>王春阳<br>
     * <b>日期：</b> 2017年8月19日 上午1:19:22 <br>
     *
     * @param url   链接地址
     * @param param 上传的数据 json字符串
     * @return
     * @throws IOException
     */
    public static String DoPostString(String url, String param) {
        PrintWriter out = null;
        BufferedReader reader = null;
        String response = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(50000);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
            String lines;
            while ((lines = reader.readLine()) != null) {
                System.out.println(lines);
                lines = new String(lines.getBytes());
                response += lines;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return response;
    }

    /**
     * <b>功能：</b> java发送post请求 数据字符形式<br>
     * <b>作者：</b>郭寅龙<br>
     * <b>日期：</b> 2018年6月1日  <br>
     *
     * @param url1  链接地址
     * @param param 上传的数据 json字符串
     * @return
     * @throws IOException
     */
    public static String DoPostStringlen(String url1, String param) throws Exception {
        String resp = null;

        System.out.println("param-----" + param);
        URL url = new URL(url1); //url地址

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);

        connection.setRequestProperty("Charset", "utf-8");

        connection.setRequestProperty("Content-Type", "application/json");

        //connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

        connection.connect();

        try (OutputStream os = connection.getOutputStream()) {
            os.write(param.getBytes("UTF-8"));
        }

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), "utf-8"))) {
            String lines;
            StringBuffer sbf = new StringBuffer();
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes());
                sbf.append(lines);
            }

            System.out.println("返回来的报文-----" + sbf.toString());
            resp = sbf.toString();

        }
        connection.disconnect();


        return resp;
    }
}